package com.swk.login.autologin;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swk.login.UserBean;

/**
 * 自动登录
 */
@WebServlet("/AutoLogin")
public class AutoLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public AutoLoginServlet() {
        super();
    }

	/**
	 * 注销入口
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 有参数false，只做检索，如果没有session，返回为空，不会创建新的session
		HttpSession session = request.getSession(false);
		if (session != null) {
			session.removeAttribute("userBean");// 移除session标记
			Cookie cookie = new Cookie("userinfo", "");//删除cookie
			cookie.setMaxAge(0);
			response.addCookie(cookie);
		}
		response.sendRedirect("/webDetail/index.jsp");
	}

	/**
	 * 自动登录
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		//获取请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String time = request.getParameter("time");
		
		//参数校验
		if (username == null || username.trim().length() == 0) {
			response.getWriter().write("账号不能为空！");
			return;
		}
		if (password == null || password.trim().length() == 0) {
			response.getWriter().write("密码不能为空！");
			return;
		}
		if (time == null || time.trim().length() == 0) {
			response.getWriter().write("时间不能为空！");
			return;
		}
		
		//数据库验证账号(假设通过了)
		if(true){
			//登录成功，将信息绑定到HttpSession域对象中
			request.getSession(true).setAttribute("userBean", new UserBean(username, password));
			//解决cookie中文乱码问题，真实项目密码应加密。
			String userinfo = URLEncoder.encode(username + "_" + password, "UTF-8");
			//向浏览器写入Cookie
			Cookie cookie = new Cookie("userinfo", userinfo);
			cookie.setMaxAge(Integer.parseInt(time) * 3600 * 24);//cookie有效期
			response.addCookie(cookie);
			
			//重定向到首页
			response.sendRedirect("/webDetail/index.jsp");
		}
		
		response.getWriter().write("账号或密码错误！");
	}

}
